<template>
  <div class="simple-security">
    <!-- 标题 -->
    <div class="header">
      <h2>安全中心</h2>
        <div>
      <el-button type="danger" @click="handleKick">批量删除</el-button>
      <el-button type="primary" @click="dialogVisible = true">分组与聚合</el-button>
        </div>
    </div>

    <!-- 简化表格 -->
    <el-table
        :data="clients"
        style="width: 100%"
        @selection-change="handleSelect"
        row-class-name="group-row"
    >
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" />

      <!-- 分组标识 -->
      <el-table-column label="所属分组" width="120">
        <template #default="scope">
          <el-tag effect="plain">
            {{ scope.row.group || '未分组' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 客户端ID -->
      <el-table-column label="ID" prop="id" width="120" />

      <!-- 设备信息 -->
      <el-table-column label="设备信息" width="180">
        <template #default="scope">
          <div class="device-info">
            <el-icon><Monitor /></el-icon>
            <span>{{ scope.row.name }}</span>
            <el-tag size="small">{{ scope.row.deviceType }}</el-tag>
          </div>
        </template>
      </el-table-column>

      <!-- 贡献度 -->
      <el-table-column label="贡献度">
        <template #default="scope">
          <div class="contribution-cell">
            <el-progress
                :percentage="scope.row.contribution"
                :color="getColor(scope.row.contribution)"
                :show-text="false"
            />
            <span class="percentage">{{ scope.row.contribution }}%</span>
          </div>
        </template>
      </el-table-column>

      <!-- 状态与操作 -->
      <el-table-column label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ statusMap[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialogVisible"
        title="客户端分组与模型聚合"
        width="600px"
    >
      <el-form :model="form" label-width="100px">
        <!-- 分组设置 -->
        <el-form-item label="分组策略">
          <el-select v-model="form.groupType" placeholder="请选择分组方式">
            <el-option
                v-for="item in groupOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 条件输入 -->
        <el-form-item
            label="分组条件"
            v-if="form.groupType === 'custom'"
        >
          <el-input
              v-model="form.groupCondition"
              placeholder="示例：contribution > 50"
          />
        </el-form-item>

        <!-- 聚合参数 -->
        <el-divider />
        <el-form-item label="聚合算法">
          <el-select v-model="form.algorithm">
            <el-option
                v-for="algo in algorithms"
                :key="algo.value"
                :label="algo.label"
                :value="algo.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学习率">
          <el-input-number
              v-model="form.learningRate"
              :min="0.001"
              :max="1"
              :step="0.01"
          />
        </el-form-item>

        <el-form-item label="聚合轮次">
          <el-input-number
              v-model="form.epochs"
              :min="1"
              :max="100"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            :loading="isProcessing"
            @click="handleSubmit"
        >
          开始处理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
// 扩展后的示例数据
const clients = ref([
  // 高贡献组
  {
    id: 'C001',
    name: '某笔记本',
    deviceType: 'Windows',
    contribution: 92,
    status: 'normal',
    group: '1'
  },
  {
    id: 'C002',
    name: '工业电脑',
    deviceType: 'Windows',
    contribution: 88,
    status: 'normal',
    group: '1'
  },

  // 中贡献组
  {
    id: 'C003',
    name: '某笔记本',
    deviceType: 'Linux',
    contribution: 65,
    status: 'normal',
    group: '1'
  },
  {
    id: 'C004',
    name: '某笔记本',
    deviceType: 'Linux',
    contribution: 58,
    status: 'normal',
    group: '2'
  },

  // 低贡献组
  {
    id: 'C005',
    name: '某笔记本',
    deviceType: 'Windows',
    contribution: 32,
    status: 'abnormal',
    group: '2'
  },
  {
    id: 'C006',
    name: '某笔记本',
    deviceType: 'Windows',
    contribution: 15,
    status: 'abnormal',
    group: '2'
  },

  // 特殊组
  {
    id: 'C007',
    name: '某笔记本',
    deviceType: 'Ubuntu',
    contribution: 95,
    status: 'normal',
    group: '3'
  },
  {
    id: 'C008',
    name: '某笔记本',
    deviceType: 'Mac',
    contribution: 78,
    status: 'normal',
    group: '3'
  }
])
// 状态映射
const statusMap = {
  normal: '正常',
  abnormal: '异常'
}

// 状态标签类型
const getStatusType = (status) => {
  return status === 'normal' ? 'success' : 'danger'
}

// 分组颜色方案
const groupColors = {
  '高贡献组': '#67C23A',
  '中贡献组': '#E6A23C',
  '低贡献组': '#F56C6C',
  '边缘计算组': '#409EFF',
  'IoT设备组': '#909399'
}

// 选中客户端
const selected = ref([])

// 新增分组聚合相关状态
const dialogVisible = ref(false)
const isProcessing = ref(false)

const form = ref({
  groupType: 'auto',
  groupCondition: '',
  algorithm: 'fedavg',
  learningRate: 0.01,
  epochs: 10
})

const groupOptions = [
  { label: '自动分组', value: 'auto' },
  { label: '按贡献度分组', value: 'contribution' },
  { label: '自定义条件', value: 'custom' }
]

const algorithms = [
  { label: '联邦平均 (FedAvg)', value: 'fedavg' },
  { label: '安全聚合 (SecureAgg)', value: 'secureagg' },
  { label: '异常过滤 (Krum)', value: 'krum' }
]

// 处理表单提交
const handleSubmit = async () => {
  try {
    isProcessing.value = true

    // 执行分组逻辑
    const groups = performGrouping()

    // 执行聚合逻辑
    await performAggregation(groups)

    ElMessage.success('操作成功完成')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error(`操作失败：${error.message}`)
  } finally {
    isProcessing.value = false
  }
}

// 执行分组
const performGrouping = () => {
  const { groupType, groupCondition } = form.value

  switch(groupType) {
    case 'auto':
      return autoGrouping()
    case 'contribution':
      return contributionGrouping()
    case 'custom':
      return customGrouping(groupCondition)
    default:
      return []
  }
}

// 自动分组逻辑（示例）
const autoGrouping = () => {
  return [clients.value] // 全部分到一组
}

// 按贡献度分组
const contributionGrouping = () => {
  const high = clients.value.filter(c => c.contribution >= 60)
  const low = clients.value.filter(c => c.contribution < 60)
  return [high, low]
}

// 自定义条件分组（简单实现）
const customGrouping = (condition) => {
  try {
    // 简单解析示例条件（实际应更严谨）
    const [field, operator, value] = condition.split(' ')
    return [
      clients.value.filter(c => eval(`c.${field} ${operator} ${value}`)),
      clients.value.filter(c => !eval(`c.${field} ${operator} ${value}`))
    ]
  } catch {
    throw new Error('条件格式不正确')
  }
}

// 模拟聚合操作
const performAggregation = async (groups) => {
  // 模拟API调用
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('聚合参数：', form.value)
      console.log('分组结果：', groups)
      resolve()
    }, 1500)
  })
}
// 颜色计算
// 修改后的颜色计算
const getColor = (percentage) => {
  return groupColors[
  clients.value.find(c => c.contribution === percentage)?.group || 'default'
      ] || '#409EFF'
}

// 选择处理
const handleSelect = (selection) => {
  selected.value = selection.map(item => item.id)
}

// 删除操作
const handleKick = () => {
  if (selected.value.length === 0) {
    alert('请先选择要删除的客户端')
    return
  }

  clients.value = clients.value.filter(
      client => !selected.value.includes(client.id)
  )
  selected.value = []
}
</script>

<style scoped>
.simple-security {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-progress {
  width: 80%;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px; /* 新增按钮间距 */
}

.el-dialog {
  border-radius: 8px;
}

.el-form-item {
  margin-bottom: 18px;
}
/* 增强样式 */
.device-info {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-icon {
    font-size: 16px;
    color: #666;
  }

  .el-tag {
    margin-left: auto;
  }
}

.contribution-cell {
  display: flex;
  align-items: center;
  gap: 12px;

  .percentage {
    min-width: 40px;
    color: #666;
  }
}

/* 分组行样式 */
:deep(.group-row) {
  td {
    background-color: rgba(245, 245, 245, 0.8);
    border-left: 4px solid transparent;

    &:first-child {
      border-left-color: v-bind('groupColors["高贡献组"]');
    }
  }

  &[data-group="高贡献组"] td {
    background-color: rgba(103, 194, 58, 0.08);
    border-left-color: v-bind('groupColors["高贡献组"]');
  }

  &[data-group="中贡献组"] td {
    background-color: rgba(230, 162, 60, 0.08);
    border-left-color: v-bind('groupColors["中贡献组"]');
  }

  &[data-group="低贡献组"] td {
    background-color: rgba(245, 108, 108, 0.08);
    border-left-color: v-bind('groupColors["低贡献组"]');
  }

  &[data-group="边缘计算组"] td {
    background-color: rgba(64, 158, 255, 0.08);
    border-left-color: v-bind('groupColors["边缘计算组"]');
  }

  &[data-group="IoT设备组"] td {
    background-color: rgba(144, 147, 153, 0.08);
    border-left-color: v-bind('groupColors["IoT设备组"]');
  }
}
</style>